﻿using mobpush.api.client;
using Nop.Core.Configuration;
using System;
using System.Collections.Generic;
using System.Text;

namespace Nop.Web.Services.Mob
{
    public class MobPushHelper
    {

        private readonly MobPushClient _client;

        public MobPushHelper(NopConfig nopConfig)
        {
            var attrs = nopConfig.MobConnectionString.Split(":");
            if (attrs.Length < 1)
                throw new Exception("Mob连接字符串错误");
            // 第一步设置基本配置信息 
            MobPushConfig.appkey = attrs[0];
            MobPushConfig.appSecret = attrs[1];

            // 第二步初始化client
            _client = new MobPushClient();

        }


        private string SendPush(string alia, string title, string context, object ext)
        {

            // 调用具体方法，如下是发送推送例
            PushWork push = new PushWork(new int[] { 1, 2 }, context, (int)PushTypeEnum.notify) //初始化基础信息
                         .buildTarget((int)TargetEnum._2, null, new string[] { alia }, null, null, null)  // 设置推送范围
                         .buildAndroid(title, (int)AndroidNotifyStyleEnum.normal, null, true, true, true) //定制android样式
                         .bulidIos(title, null, null, 1, null, null, null, null) //定制ios设置
                         .buildExtra(1, JsonExtension.ToJSON(ext), 1) // 设置扩展信息
                         ;
            // 发送推送消息
            string batchId = _client.push(push);
            return batchId;
        }

        private string SendMessage(string alia, string title, string context, object ext)
        {
            // 调用具体方法，如下是发送推送例
            PushWork push = new PushWork(new int[] { 1, 2 }, context, (int)PushTypeEnum.custom) //初始化基础信息
                         .buildTarget((int)TargetEnum._2, null, new string[] { alia }, null, null, null)  // 设置推送范围
                         .buildAndroid(title, (int)AndroidNotifyStyleEnum.normal, null, true, true, true) //定制android样式
                         .bulidIos(title, null, null, 1, null, null, null, null) //定制ios设置
                         .buildExtra(1, JsonExtension.ToJSON(ext), 1) // 设置扩展信息
                         ;
            // 发送推送消息
            string batchId = _client.push(push);
            return batchId;
        }


        public void Send(string alia, string title, string context, object ext) {
            try
            {
                SendPush(alia, title, context, ext);
            }
            catch (Exception ex)
            {  
            }
            try
            {
                SendMessage(alia, title, context, ext);
            }
            catch (Exception ex)
            { 
            }
        }
    }
}
